<template>
  <div class="map-view">
    <div :id="localUUID" class="maps"></div>
  </div>
</template>
<script>
import { Scene, Popup, Marker, MarkerLayer } from '@antv/l7'
import { GaodeMap } from '@antv/l7-maps'
import { createUUID } from '@/common/js/mUtils'
// import { post } from '@/api/fetch'

const popup = new Popup({
  anchor: 'top-right',
  closeButton: false,
  maxWidth: 332,
  closeOnClick: true
})
const popupROLL = new Popup({
  anchor: 'top-right',
  closeButton: false,
  maxWidth: 332,
  closeOnClick: true
})
export default {
  name: 'MMaptype1',
  props: {
    props: {
      type: Array,
      default: function() {
        return [
          {
            fields: []
          }
        ]
      }
    },
    width: {
      type: Number,
      default: 300
    },
    height: {
      type: Number,
      default: 300
    },
    ratio: {
      type: Number,
      default: 1
    },
    uuid: String
  },
  data() {
    return {
      scene: null,
      popup: null,
      popupROLLstate: true,
      trucksLayer: null,
      Interval: null,
      receiveName: '',
      destination: '',
      datas: [],
      mapobj: [],
      unitcount: 0,
      gisData: [], // 地图中 的数据
      C1Data: [], // 汽队数据
      C2Data: [], // 车队数据
      OriginalC2Data: [], // 汽队车牌号信息
      showItemWindow: false,
      plateNumber: '', // 车牌号
      fetchcount: 0, // 递归计数器
      timer: null,
      localUUID: createUUID()
    }
  },
  computed: {
    dataTrigger() {
      if (this.props[1].fields[0].value.dataJson.json) {
        const result = this.props[1].fields[0].value.dataJson.json
        let dataobj = '{}'
        try {
          dataobj = JSON.parse(result)
        } catch (e) {
          this.$message.error('JSON格式有误请重试')
          dataobj = {}
        }
        return dataobj
      } else {
        return []
      }
    },
    modelTrigger() {
      return this.props[1].fields[0].value.dataJson.model
    },
    getMapStyle() {
      return this.props[0].fields[3].value[0].value.value
    },
    getZoom() {
      return this.props[0].fields[3].value[1].value.value
    },
    getX() {
      return this.props[0].fields[3].value[2].value.value
    },
    getY() {
      return this.props[0].fields[3].value[3].value.value
    }
    // getpitch() {
    // 	return this.props[0].fields[3].value[4].value.value;
    // },
  },
  watch: {
    dataTrigger(val) {
      if (val && this.scene) {
        this.drawTrucksFn(val)
      }
    },
    modelTrigger(val) {
      if (this.scene) {
        this.drawTrucksFn(this.dataTrigger)
      }
    },
    getMapStyle(val) {
      this.scene.setMapStyle(val)
    },
    getZoom(val) {
      this.scene.setZoom(val)
    },
    getX(val) {
      this.scene.setCenter([val, this.getY])
    },
    getY(val) {
      this.scene.setCenter([this.getX, val])
    }
    // getpitch(val) {
    // 	this.scene.setPitch(val);
    // },
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
    clearTimeout(this.timer)
    this.scene && this.scene.destroy()
  },
  methods: {
    setZoom(val) {
      this.props[0].fields[3].value[1].value.value = val
    },
    setX(val) {
      this.props[0].fields[3].value[2].value.value = val
    },
    setY(val) {
      this.props[0].fields[3].value[3].value.value = val
    },
    // setpitch(val) {
    // 	this.props[0].fields[3].value[4].value.value = val;
    // },
    changecondition(receiveName, destination) {
      this.receiveName = receiveName
      this.destination = destination
      this.initMap()
    },
    searchCar(target) {
      let bo = false
      this.gisData.forEach(item => {
        if (item.vnum === target) {
          bo = true
          this.scene.setZoomAndCenter(12.5, [item.location_x || 116.397428, item.location_y || 39.90923])
          this.createPopup(item)
        }
      })
      if (!bo) {
        this.$message({
          message: '查询不到该车辆定位，请稍后再试！',
          type: 'error'
        })
      }
    },
    sameUnit() {
      this.createPopup(this.datas[this.unitcount])
    },
    initMap() {
      this.scene && this.scene.destroy()
      this.fetchcount = 0
      const mapoption = {
        center: [this.getX, this.getY], // 地图初始中心经纬度 {Lnglat}
        pitch: 0, // 地图初始俯仰角度 {number}  default 0
        style: this.getMapStyle, // 简化地图样式设置，dark,light,normal,blank 无底图
        zoom: this.getZoom, // 地图初始显示级别 {number} Mapbox （0-24） 高德 （2-19）
        minZoom: 2, // 最小缩放等级
        maxZoom: 15 // 最大缩放等级
        // style: "amap://styles/e3aca27baf29d44cbe238dd9312ca88b?isPublic=true",
      }
      const map = new GaodeMap(mapoption)
      const scene = new Scene({
        id: this.localUUID, // 容器ID
        logoVisible: false, // 是否显示logo
        map: map
      })
      this.map = map
      this.scene = scene
      this.popup = popup
      this.popupROLL = popup

      scene.on('loaded', () => {
        this.drawTrucksFn(this.dataTrigger)
        scene.addPopup(popup)
        scene.addPopup(popupROLL)
        scene.on('moveend', () => {
          const pos = this.scene.getCenter()
          this.setX(pos.lng)
          this.setY(pos.lat)
        })
        scene.on('zoomend', () => {
          setTimeout(() => {
            this.setZoom(scene.getZoom() + 1)
          }, 1000)
        })
      }) // 地图加载完成触发
    },
    // 绘制卡车
    drawTrucksFn(data) {
      // if (JSON.stringify(data) == JSON.stringify(this.C1Data)) {
      // 	console.log("不重绘");
      // 	return "";
      // }
      clearInterval(this.Interval)
      this.unitcount = 0
      const scene = this.scene
      let trucksLayer = this.trucksLayer
      if (trucksLayer) {
        // scene.removeMarkerLayer(existedTrucksLayer)
        // return
        trucksLayer && trucksLayer.scene && trucksLayer.clear()
      } else {
        trucksLayer = new MarkerLayer()
        this.trucksLayer = trucksLayer
      }
      // 请求车辆数据
      this.fetchGis(data)
    },
    // 加入卡车BG
    initPopup(item, scene, trucksLayer) {
      var el = document.createElement('div')
      var el2html = `
          <div class="truck-mark1" style="transform:rotate(${Math.ceil(Math.random() * 360)}deg)"></div>`
      el.className = 'truckclass'
      // el.textContent = item.name;
      el.innerHTML = el2html
      const marker = new Marker({
        element: el,
        extData: item
      }).setLnglat([item.location_x, item.location_y])

      marker.on('mouseover', async e => {
        // 获取地理坐标
        const positionCN = ''

        let popHtml = ''
        popHtml = `
            <div class="truck-pop">
              <div class="number"><div class='dino'></div><span class="item-name">车牌号</span>${e.data.vnum}</div>
              <div class="truck-cont">
                <div class="item current"><div class='dino'></div><div class="item-name">运单ID</div><div class="item-data">${e
                  .data.id || ''}</div></div>
                <div class="item current ${
                  e.data.person ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">承运司机&emsp;</div><div class="item-data">${e.data
          .person || ''}</div></div>
                <div class="item current ${
                  e.data.tel ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">承运手机号&emsp;</div><div class="item-data">${e.data
          .tel || ''}</div></div>
                <div class="item current ${
                  positionCN ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">当前定位&emsp;</div><div class="item-data">${positionCN ||
          ''}</div></div>
              </div>
            </div>
          `
        popup.setHTML(popHtml)
        popup.setLnglat([e.data.location_x, e.data.location_y])
        popup.open()
        // this.popupROLLstate = false
        popupROLL.close()
      })
      // marker.on('mouseout', e => {
      //   popup.close()
      //   this.popupROLLstate = true
      //   // popupROLL.open()
      // })
      trucksLayer.addMarker(marker)
      scene.addMarkerLayer(trucksLayer)
      // this.datas[0] && this.createPopup(this.datas[0])
    },
    // 打开指定Popup
    async createPopup(dataunit) {
      const scene = this.scene
      const e = dataunit || []
      // if (!e.location_x || !e.location_y) return
      // const marker = new Marker({}).setLnglat([e.location_x, e.location_y])
      let popHtml = ''
      const positionCN = ''

      popHtml = `
            <div class="truck-pop">
              <div class="number"><div class='dino'></div><span class="item-name">车牌号</span>${e.vnum || ''}</div>
              <div class="truck-cont">
                <div class="item current"><div class='dino'></div><div class="item-name">运单ID</div><div class="item-data">${e.id ||
                  ''}</div></div>
                <div class="item current ${
                  e.person ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">承运司机&emsp;</div><div class="item-data">${e.person ||
        ''}</div></div>
                <div class="item current ${
                  e.tel ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">承运手机号&emsp;</div><div class="item-data">${e.tel ||
        ''}</div></div>
                <div class="item current ${
                  positionCN ? '' : 'none'
                }"><div class='dino'></div><div class="item-name">当前定位&emsp;</div><div class="item-data">${positionCN ||
        ''}</div></div>
              </div>
            </div>
          `
      popupROLL.setHTML(popHtml)
      popupROLL.setLnglat([e.location_x, e.location_y])
      this.popupROLLstate && scene.addPopup(popupROLL)
    },
    fetchGis(data) {
      this.C1Data = []
      const tempdata = data || []
      if (Array.isArray(tempdata)) {
        tempdata.forEach(item => {
          if (item.location_x && item.location_y) {
            this.C1Data.push(item)
            this.initPopup(item, this.scene, this.trucksLayer)
            this.collectionData()
          }
        })
        // this.reDraw()
      }
    },
    refetch(a, b, c) {
      this.fetchqueryLocationByPlateNumberAndTime(a, b, c)
    },
    collectionData() {
      if (Array.isArray(this.C1Data) && Array.isArray(this.C2Data)) {
        this.gisData = [...this.C1Data, ...this.C2Data]
      } else if (Array.isArray(this.C1Data) && !Array.isArray(this.C2Data)) {
        this.gisData = this.C1Data
      } else if (Array.isArray(this.C2Data) && !Array.isArray(this.C1Data)) {
        this.gisData = this.C2Data
      } else {
        this.gisData = []
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
.map-view
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    position: relative;
    margin: 10px;
.maps
    width 100%
    height 100%
>>>.l7-popup {
  .l7-popup-tip { border: 0;}
  .l7-popup-content { padding: 0; background: none;}
}
>>>.truck-mark1 {
  width:19px;
  height: 44px;
  background-image:url('../../../assets/mapimg/t.png');
  position: relative;
  background-size:cover;
}
>>>.truck-mark2 {
  width:19px;
  height: 44px;
  background-image:url('../../../assets/mapimg/t.png');
  position: relative;
  background-size:cover;
}
>>>.truck-pop {
  width: 332px;
  height: auto;
  border #5086FC 1px solid
  border-radius 6px
  box-sizing: border-box;
  background rgba(0,0,0,0.5)
  box-shadow: 0px 1px 18px 0px rgba(80, 134, 252, 0.5);
  color: #fff;
    .truck-cont{
      padding-top 5px
    }
    .number {
      font-size: 16px;
      line-height: 40px;
      height 40px;
      padding:0 10px;
      white-space: nowrap;
      text-overflow:ellipsis;
      overflow: hidden;
      border-bottom #5086FC 1px solid
      display: flex;
    }
    .item {
      padding:0 10px 7px 10px;
      font-size: 16px;
      position: relative;
      min-height: 32px;
      line-height: 32px;
      display: flex;
    }
    .item-name{
      margin-right 10px
      width 105px
    }
    .item-data{
      width 170px
      line-height: 22px
      padding-top:5px
      }
  }
>>>.dino{
  background-size:cover
  height 32px
  width 10px
  margin: 0 10px 0 0;
}
>>>.none{
  display: none !important;
}
</style>
